# -*- coding: utf-8 -*-
import json
import binascii
from hashlib import md5, sha1
from Crypto.Cipher import AES
import requests
from string import ascii_letters, digits
from random import choice


api_key = 'PpNUAonI'
api_secret_key = 'ouq4Jvgz24W2EDFsBiCKIwkyue8zeTIZSoTe2NaTSre8Ec13N819GTFyLx9CpiVURVL'
#nonce = '12345678901234567890'



def random_str(length=4):
    char = ascii_letters + digits
    return "".join(choice(char) for _ in range(length))


def get_sha1(*args):
    try:
        sort_list = map(lambda x: str(x), args)
        sort_list.sort()
        sha = sha1()
        sha.update("".join(sort_list))
        return sha.hexdigest().upper()
    except Exception():
        return None


def encrypt(api_key, api_secret_key, nonce, raw):
    key = md5(api_key + nonce).hexdigest()[::-2]
    iv = md5(nonce + api_secret_key).hexdigest()[::-2]
    raw += (16 - len(raw) % 16) * '\0'
    generator = AES.new(key, AES.MODE_CBC, IV=iv)
    return binascii.b2a_hex(generator.encrypt(raw))



def decrypt(api_key, api_secret_key, nonce, enc):
    key = md5(api_key + nonce).hexdigest()[::-2]
    iv = md5(nonce + api_secret_key).hexdigest()[::-2]
    enc = binascii.unhexlify(enc)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    try:
        return 0, json.loads(cipher.decrypt(enc).decode('utf-8').rstrip("\0"))
    except (SyntaxError, NameError):
        return -40008, None

def get_result(uid):
    data = {'uid': uid}
    nonce = random_str(25)
# 生成随机字符串
    s = encrypt(api_key, api_secret_key, nonce, json.dumps(data))
    msg_signature = get_sha1(nonce, s, api_key)
    timeout = (100, 100)
#target_url = 'http://xiaosiapi.deepmatrix.cn/api/wx_card/accesscontrol'  # 拼接url relative_path='api/isp/info'
    target_url = 'http://xiaosiapi.mindaxiaosi.com/api/urp/all_scr_without_pwd'  # 拼接url relative_path='api/isp/info'
    for i in range(1):
        req = requests.post(
             url=target_url,
             params={'nonce': nonce, 'msg_signature': msg_signature},
             data={'encrypt_msg': s, 'api_key': api_key},
             timeout=timeout)

        # print(req.status_code)

        if req.status_code == 200:
         raw_data = req.json()
         # print(raw_data)
         data = decrypt(api_key, api_secret_key, raw_data['nonce'], raw_data['encrypt_msg'])
         # print(type(data[1]))


         # print (data)
         # result = data.decode("unicode-escape")

    return data[1]


